from flask import Blueprint, render_template, current_app, request
from .db import get_db
import time

frontend = Blueprint("frontend", __name__)

@frontend.route("/")
def index():
    return "ok"

@frontend.route("/buy")
def buy():
    q = request.values.get("quantity", 1)
    try:
        quantity = int(q)
    except:
        quantity = 1
    pid = "20150001"
    conn = get_db()
    cur =conn.cursor()
    sql = """select
        productname, productdesc, price, discount
        from product
    where
        productno = '%s'
    """ % pid
    cur.execute(sql)
    rs = cur.fetchall()
    cur.close()
    if not rs:
        cur.close()
        return "Not found", 404
    productname, productdesc, price, discount = rs[0]
    total_fee = float(price) * quantity - abs(float(discount)) * quantity
    total_fee = "%.2f" % float(total_fee)
    price = "%.2f" % float(price)
    discount = "%.2f" % float(discount)
    return render_template("buy.html", **locals())

@frontend.route("/t")
def t():
    date = request.values.get("date", "")
    if not date:
        date = time.strftime("%Y-%m-%d")
    return render_template("t.html", date=date)
